<template>
  <div class="deposit-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>保证金管理</h1>
        <p>管理服务保证金，确保服务质量和平台信誉</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showDepositDialog">
          <el-icon><Plus /></el-icon>
          充值保证金
        </el-button>
      </div>
    </div>

    <!-- 保证金概览 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card total">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(depositStats.totalDeposit) }}</div>
              <div class="stat-label">总保证金</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card frozen">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(depositStats.frozenDeposit) }}</div>
              <div class="stat-label">冻结保证金</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card available">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(depositStats.availableDeposit) }}</div>
              <div class="stat-label">可用保证金</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card pending">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(depositStats.pendingRefund) }}</div>
              <div class="stat-label">待退还保证金</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 服务保证金要求 -->
    <el-card class="deposit-requirements-card">
      <template #header>
        <div class="card-header">
          <span>各服务类型保证金要求</span>
          <el-tag type="info">发布服务前需缴纳相应保证金</el-tag>
        </div>
      </template>

      <div class="requirements-grid">
        <div v-for="service in serviceTypes" :key="service.type" class="requirement-item">
          <div class="service-icon" :class="getServiceIconClass(service.type)">
            <el-icon><component :is="getServiceIcon(service.type)" /></el-icon>
          </div>
          <div class="service-info">
            <div class="service-name">{{ service.name }}</div>
            <div class="service-desc">{{ service.description }}</div>
            <div class="deposit-amount">保证金：¥{{ service.deposit }}</div>
          </div>
          <div class="service-status">
            <el-tag :type="getDepositStatusType(service.type)">
              {{ getDepositStatusText(service.type) }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 保证金记录 -->
    <el-card class="deposit-records-card">
      <template #header>
        <div class="card-header">
          <span>保证金记录</span>
          <div class="header-filters">
            <el-select v-model="filterType" placeholder="记录类型" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option label="充值" value="deposit" />
              <el-option label="冻结" value="freeze" />
              <el-option label="解冻" value="unfreeze" />
              <el-option label="扣除" value="deduct" />
              <el-option label="退还" value="refund" />
            </el-select>
            <el-button @click="exportRecords">
              <el-icon><Download /></el-icon>
              导出记录
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredRecords" style="width: 100%" v-loading="recordsLoading">
        <el-table-column prop="recordId" label="记录号" width="160" />
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getRecordTypeColor(scope.row.type)">
              {{ getRecordTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="scope">
            <span :class="getAmountClass(scope.row.type)">
              {{ getAmountPrefix(scope.row.type) }}¥{{ formatMoney(scope.row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="serviceType" label="服务类型" width="120">
          <template #default="scope">
            <span v-if="scope.row.serviceType">{{ getServiceTypeName(scope.row.serviceType) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" min-width="200" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusColor(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="160" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewRecordDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 扣款优先级设置 -->
    <el-card class="deduction-settings-card">
      <template #header>
        <div class="card-header">
          <span>扣款优先级设置</span>
          <el-tag type="warning">发生罚款时的扣款顺序</el-tag>
        </div>
      </template>

      <div class="deduction-settings">
        <div class="setting-item">
          <span class="setting-label">扣款优先级：</span>
          <el-radio-group v-model="deductionPriority" @change="saveDeductionSettings">
            <el-radio label="balance_first">优先扣除可提现余额</el-radio>
            <el-radio label="deposit_first">优先扣除保证金</el-radio>
          </el-radio-group>
        </div>
        <div class="setting-desc">
          <p v-if="deductionPriority === 'balance_first'">
            发生罚款时，优先从可提现余额中扣除，余额不足时再从保证金中扣除
          </p>
          <p v-else>
            发生罚款时，优先从保证金中扣除，保证金不足时再从可提现余额中扣除
          </p>
        </div>
      </div>
    </el-card>

    <!-- 充值保证金对话框 -->
    <el-dialog
      v-model="depositDialogVisible"
      :title="paymentStep === 'form' ? '充值保证金' : '完成支付'"
      width="600px"
      @close="resetDepositForm"
    >
      <!-- 充值表单 -->
      <div v-if="paymentStep === 'form'">
        <el-form
          ref="depositFormRef"
          :model="depositForm"
          :rules="depositRules"
          label-width="100px"
        >
          <el-form-item label="服务类型" prop="serviceType">
            <el-select v-model="depositForm.serviceType" placeholder="请选择服务类型" style="width: 100%;">
              <el-option
                v-for="service in serviceTypes"
                :key="service.type"
                :label="service.name"
                :value="service.type"
                :disabled="isServiceDepositPaid(service.type)"
              >
                <span>{{ service.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px;">¥{{ service.deposit }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="充值金额" prop="amount">
            <el-input-number
              v-model="depositForm.amount"
              :min="getMinDepositAmount()"
              :precision="2"
              controls-position="right"
              style="width: 100%;"
              placeholder="请输入充值金额"
            />
            <div class="form-tips">
              <div class="form-tip" v-if="depositForm.serviceType">
                最低充值金额：¥{{ getRequiredDeposit(depositForm.serviceType) }}
              </div>
            </div>
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-radio-group v-model="depositForm.paymentMethod">
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="wechat">微信支付</el-radio>
              <el-radio label="bank">银行卡</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- 支付页面 -->
      <div v-if="paymentStep === 'payment'" class="payment-section">
        <div class="payment-header">
          <div class="payment-info">
            <h3>{{ getServiceTypeName(currentDepositOrder.serviceType) }} 保证金</h3>
            <p class="amount">支付金额：¥{{ currentDepositOrder.amount }}</p>
            <p class="order-id">订单号：{{ currentDepositOrder.orderId }}</p>
          </div>
          <div class="payment-timer">
            <el-icon><Timer /></el-icon>
            <span>{{ formatTime(depositRemainingTime) }}</span>
          </div>
        </div>

        <!-- 支付宝支付 -->
        <div v-if="depositPaymentInfo.type === 'alipay'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#1677ff"><Money /></el-icon>
            <span>支付宝支付</span>
          </div>
          <div class="qr-section">
            <div class="qr-code">
              <img :src="generateQRCode(depositPaymentInfo.qrCode)" alt="支付宝二维码" />
            </div>
            <div class="qr-instructions">
              <p>请使用支付宝扫描二维码完成支付</p>
              <p>支付完成后系统将自动确认到账</p>
              <p>请勿关闭此页面</p>
            </div>
          </div>
          <div class="payment-actions">
            <el-button @click="openDepositAlipay">打开支付宝支付</el-button>
          </div>
        </div>

        <!-- 微信支付 -->
        <div v-if="depositPaymentInfo.type === 'wechat'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#07c160"><ChatDotRound /></el-icon>
            <span>微信支付</span>
          </div>
          <div class="qr-section">
            <div class="qr-code">
              <img :src="generateQRCode(depositPaymentInfo.qrCode)" alt="微信支付二维码" />
            </div>
            <div class="qr-instructions">
              <p>请使用微信扫描二维码完成支付</p>
              <p>支付完成后系统将自动确认到账</p>
              <p>请勿关闭此页面</p>
            </div>
          </div>
          <div class="payment-actions">
            <el-button @click="openDepositWechat">打开微信支付</el-button>
          </div>
        </div>

        <!-- 银行卡支付 -->
        <div v-if="depositPaymentInfo.type === 'bank'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#f56c6c"><CreditCard /></el-icon>
            <span>银行卡支付</span>
          </div>
          <div class="bank-section">
            <p class="bank-instruction">点击下方按钮跳转到银行支付页面</p>
            <p class="bank-instruction">支付完成后系统将自动确认到账</p>
            <div class="payment-actions">
              <el-button type="primary" size="large" @click="openDepositBankPay">
                前往银行支付页面
              </el-button>
            </div>
          </div>
        </div>

        <!-- 支付状态检查 -->
        <div v-if="checkingDepositPayment" class="payment-status">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在确认支付状态...</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDepositPayment">
            {{ paymentStep === 'form' ? '取消' : '取消支付' }}
          </el-button>
          <el-button
            v-if="paymentStep === 'form'"
            type="primary"
            :loading="depositSubmitting"
            @click="submitDeposit"
          >
            确认充值
          </el-button>
          <el-button
            v-if="paymentStep === 'payment'"
            type="text"
            @click="refreshDepositPaymentStatus"
          >
            刷新状态
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Wallet,
  Lock,
  Money,
  Clock,
  Download,
  Star,
  Timer,
  List,
  User,
  Tools,
  ChatDotRound,
  CreditCard,
  Loading
} from '@element-plus/icons-vue'
import {
  getDepositStats,
  getDepositRecords,
  getDepositRecordDetail,
  payDeposit,
  getServiceDepositRequirements,
  getPaidServiceTypes,
  getDeductionPriority,
  updateDeductionPriority,
  exportDepositRecords,
  checkDepositPaymentStatus,
  DEPOSIT_RECORD_TYPES,
  DEPOSIT_RECORD_TYPE_TEXT,
  DEPOSIT_RECORD_TYPE_COLOR,
  DEPOSIT_STATUS,
  DEPOSIT_STATUS_TEXT,
  DEPOSIT_STATUS_COLOR,
  DEDUCTION_PRIORITY,
  SERVICE_DEPOSIT_CONFIG,
  getRecordTypeColor,
  getRecordTypeText,
  getStatusColor,
  getStatusText,
  getAmountPrefix,
  getAmountClass,
  getServiceTypeName,
  getServiceDepositAmount
} from '@/api/deposit'

// 路由
const router = useRouter()

// 响应式数据
const recordsLoading = ref(false)
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(0)
const depositDialogVisible = ref(false)
const depositSubmitting = ref(false)
const depositFormRef = ref()
const deductionPriority = ref('balance_first')

// 支付相关状态
const paymentStep = ref('form') // 'form' | 'payment'
const currentDepositOrder = ref(null)
const depositPaymentInfo = ref(null)
const checkingDepositPayment = ref(false)
const depositRemainingTime = ref(0)
const depositPaymentTimer = ref(null)

// 保证金统计
const depositStats = reactive({
  totalDeposit: 0,
  frozenDeposit: 0,
  availableDeposit: 0,
  pendingRefund: 0
})

// 服务类型和保证金要求
const serviceTypes = ref([])

// 已缴纳保证金的服务类型
const paidServiceTypes = ref([])

// 保证金记录
const depositRecords = ref([])

// 充值表单
const depositForm = reactive({
  serviceType: '',
  amount: 0,
  paymentMethod: 'alipay'
})

// 表单验证规则
const depositRules = {
  serviceType: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value <= 0) {
          callback(new Error('充值金额必须大于0'))
        } else if (depositForm.serviceType && value < getRequiredDeposit(depositForm.serviceType)) {
          callback(new Error(`最低充值金额为¥${getRequiredDeposit(depositForm.serviceType)}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 计算属性
const filteredRecords = computed(() => {
  if (!filterType.value) {
    return depositRecords.value
  }
  return depositRecords.value.filter(record => record.type === filterType.value)
})

// 获取保证金统计数据
const getDepositStatsData = async () => {
  try {
    const response = await getDepositStats()
    if (response.code === 200) {
      const data = response.data
      depositStats.totalDeposit = data.totalDeposit || 0
      depositStats.frozenDeposit = data.frozenDeposit || 0
      depositStats.availableDeposit = data.availableDeposit || 0
      depositStats.pendingRefund = data.pendingRefund || 0
    } else {
      throw new Error(response.message || '获取保证金统计失败')
    }
  } catch (error) {
    console.error('获取保证金统计失败:', error)
    ElMessage.error(error.message || '获取保证金统计失败')
  }
}

// 获取服务类型保证金要求
const getServiceTypesData = async () => {
  try {
    const response = await getServiceDepositRequirements()
    if (response.code === 200) {
      serviceTypes.value = response.data || Object.values(SERVICE_DEPOSIT_CONFIG)
    } else {
      // 使用默认配置
      serviceTypes.value = Object.values(SERVICE_DEPOSIT_CONFIG)
    }
  } catch (error) {
    console.error('获取服务类型失败:', error)
    // 使用默认配置
    serviceTypes.value = Object.values(SERVICE_DEPOSIT_CONFIG)
  }
}

// 获取已缴纳保证金的服务类型
const getPaidServiceTypesData = async () => {
  try {
    const response = await getPaidServiceTypes()
    if (response.code === 200) {
      paidServiceTypes.value = response.data || []
    } else {
      throw new Error(response.message || '获取已缴纳服务类型失败')
    }
  } catch (error) {
    console.error('获取已缴纳服务类型失败:', error)
    paidServiceTypes.value = []
  }
}

// 获取保证金记录数据
const getDepositRecordsData = async () => {
  try {
    recordsLoading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      type: filterType.value || undefined
    }

    const response = await getDepositRecords(params)
    if (response.code === 200) {
      depositRecords.value = response.data.records || response.data || []
      totalRecords.value = response.data.total || depositRecords.value.length
    } else {
      throw new Error(response.message || '获取保证金记录失败')
    }
  } catch (error) {
    console.error('获取保证金记录失败:', error)
    ElMessage.error(error.message || '获取保证金记录失败')
    depositRecords.value = []
    totalRecords.value = 0
  } finally {
    recordsLoading.value = false
  }
}

// 获取扣款优先级设置
const getDeductionPriorityData = async () => {
  try {
    const response = await getDeductionPriority()
    if (response.code === 200) {
      deductionPriority.value = response.data.priority || 'balance_first'
    } else {
      throw new Error(response.message || '获取扣款优先级失败')
    }
  } catch (error) {
    console.error('获取扣款优先级失败:', error)
    deductionPriority.value = 'balance_first'
  }
}

// 方法
const formatMoney = (amount) => {
  return (amount || 0).toLocaleString()
}

const getServiceIcon = (type) => {
  const iconMap = {
    'laundry': 'User',
    'shoes': 'Star',
    'pet': 'Timer',
    'bag': 'List',
    'bedding': 'Star',
    'car': 'Star',
    'home_cleaning': 'Tools',
    'plumbing': 'Tools'
  }
  return iconMap[type] || 'Star'
}

const getServiceIconClass = (type) => {
  const classMap = {
    'laundry': 'icon-laundry',
    'shoes': 'icon-shoes',
    'pet': 'icon-pet',
    'bag': 'icon-bag',
    'bedding': 'icon-bedding',
    'car': 'icon-car',
    'home_cleaning': 'icon-home',
    'plumbing': 'icon-plumbing'
  }
  return classMap[type] || 'icon-default'
}

const getRequiredDeposit = (serviceType) => {
  const service = serviceTypes.value.find(s => s.type === serviceType)
  return service ? service.deposit : 0
}

const isServiceDepositPaid = (serviceType) => {
  return paidServiceTypes.value.includes(serviceType)
}

const getDepositStatusType = (serviceType) => {
  return isServiceDepositPaid(serviceType) ? 'success' : 'warning'
}

const getDepositStatusText = (serviceType) => {
  return isServiceDepositPaid(serviceType) ? '已缴纳' : '未缴纳'
}

const showDepositDialog = () => {
  depositDialogVisible.value = true
}

const resetDepositForm = () => {
  if (depositFormRef.value) {
    depositFormRef.value.resetFields()
  }
  Object.assign(depositForm, {
    serviceType: '',
    amount: 0,
    paymentMethod: 'alipay'
  })

  // 重置支付状态
  paymentStep.value = 'form'
  currentDepositOrder.value = null
  depositPaymentInfo.value = null
  checkingDepositPayment.value = false
  depositRemainingTime.value = 0

  // 清除定时器
  if (depositPaymentTimer.value) {
    clearInterval(depositPaymentTimer.value)
    depositPaymentTimer.value = null
  }
}

const getMinDepositAmount = () => {
  if (depositForm.serviceType) {
    return getRequiredDeposit(depositForm.serviceType)
  }
  return 0
}

const submitDeposit = async () => {
  if (!depositFormRef.value) return

  try {
    await depositFormRef.value.validate()
    depositSubmitting.value = true

    const response = await payDeposit({
      serviceType: depositForm.serviceType,
      amount: depositForm.amount,
      paymentMethod: depositForm.paymentMethod
    })

    if (response.code === 200) {
      // 保存订单和支付信息
      currentDepositOrder.value = response.data
      depositPaymentInfo.value = response.data.paymentInfo

      // 计算剩余时间
      const expireTime = new Date(response.data.expireTime).getTime()
      const now = new Date().getTime()
      depositRemainingTime.value = Math.max(0, Math.floor((expireTime - now) / 1000))

      // 切换到支付页面
      paymentStep.value = 'payment'

      // 开始倒计时
      startDepositPaymentTimer()

      ElMessage.success('保证金订单创建成功，请完成支付')
      ElMessage.info('请在第三方支付平台完成支付，支付完成后点击"刷新状态"查看结果')
    } else if (response.code === 403) {
      // 需要绑定银行卡或身份证认证
      if (response.data?.requireBankCard) {
        ElMessageBox.confirm(
          '保证金缴纳需要先绑定银行卡，是否前往绑定？',
          '需要绑定银行卡',
          {
            confirmButtonText: '前往绑定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 关闭当前对话框
          depositDialogVisible.value = false
          resetDepositForm()
          // 跳转到银行卡绑定页面
          router.push('/main/settings/bankcard')
        }).catch(() => {
          // 用户取消
        })
      } else if (response.data?.requireIdCard) {
        ElMessageBox.confirm(
          '保证金缴纳需要先完成身份证实名认证，是否前往认证？',
          '需要身份证认证',
          {
            confirmButtonText: '前往认证',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 关闭当前对话框
          depositDialogVisible.value = false
          resetDepositForm()
          // 跳转到银行卡绑定页面
          router.push('/main/settings/bankcard')
        }).catch(() => {
          // 用户取消
        })
      } else {
        ElMessage.error(response.message || '保证金缴纳失败')
      }
    } else {
      throw new Error(response.message || '创建保证金订单失败')
    }
  } catch (error) {
    console.error('创建保证金订单失败:', error)
    ElMessage.error(error.message || '创建保证金订单失败，请重试')
  } finally {
    depositSubmitting.value = false
  }
}

// 保存扣款优先级设置
const saveDeductionSettings = async () => {
  try {
    const response = await updateDeductionPriority(deductionPriority.value)
    if (response.code === 200) {
      ElMessage.success('扣款优先级设置已保存')
    } else {
      throw new Error(response.message || '保存设置失败')
    }
  } catch (error) {
    console.error('保存扣款优先级失败:', error)
    ElMessage.error(error.message || '保存设置失败')
  }
}

// 导出保证金记录
const exportRecords = async () => {
  try {
    const params = {
      type: filterType.value || undefined
    }

    const response = await exportDepositRecords(params)

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `保证金记录_${new Date().toISOString().split('T')[0]}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('保证金记录导出成功')
  } catch (error) {
    console.error('导出保证金记录失败:', error)
    ElMessage.error(error.message || '导出失败')
  }
}

// 查看记录详情
const viewRecordDetail = async (record) => {
  try {
    const response = await getDepositRecordDetail(record.recordId)
    if (response.code === 200) {
      const detail = response.data
      let content = `记录号：${detail.recordId}\n`
      content += `类型：${getRecordTypeText(detail.type)}\n`
      content += `金额：${getAmountPrefix(detail.type)}¥${formatMoney(detail.amount)}\n`
      content += `服务类型：${detail.serviceType ? getServiceTypeName(detail.serviceType) : '-'}\n`
      content += `说明：${detail.description}\n`
      content += `状态：${getStatusText(detail.status)}\n`
      content += `时间：${detail.createTime}\n`

      if (detail.remark) {
        content += `备注：${detail.remark}\n`
      }

      ElMessageBox.alert(content, '保证金记录详情', {
        confirmButtonText: '确定'
      })
    } else {
      throw new Error(response.message || '获取记录详情失败')
    }
  } catch (error) {
    console.error('获取记录详情失败:', error)
    // 使用基本信息作为备用
    ElMessageBox.alert(
      `记录号：${record.recordId}\n类型：${getRecordTypeText(record.type)}\n金额：${getAmountPrefix(record.type)}¥${formatMoney(record.amount)}\n说明：${record.description}\n状态：${getStatusText(record.status)}\n时间：${record.createTime}`,
      '保证金记录详情',
      {
        confirmButtonText: '确定'
      }
    )
  }
}

const handleSizeChange = async (val) => {
  pageSize.value = val
  currentPage.value = 1
  await getDepositRecordsData()
}

const handleCurrentChange = async (val) => {
  currentPage.value = val
  await getDepositRecordsData()
}

// 支付相关函数
const startDepositPaymentTimer = () => {
  if (depositPaymentTimer.value) {
    clearInterval(depositPaymentTimer.value)
  }

  depositPaymentTimer.value = setInterval(() => {
    if (depositRemainingTime.value > 0) {
      depositRemainingTime.value--
    } else {
      clearInterval(depositPaymentTimer.value)
      ElMessage.warning('支付已超时，请重新发起充值')
      cancelDepositPayment()
    }
  }, 1000)
}

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const generateQRCode = (content) => {
  return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(content)}`
}

const openDepositAlipay = () => {
  if (depositPaymentInfo.value?.payUrl) {
    if (validatePaymentUrl(depositPaymentInfo.value.payUrl)) {
      window.open(depositPaymentInfo.value.payUrl, '_blank')
    } else {
      ElMessage.error('支付链接不安全，请联系客服')
      console.warn('Untrusted payment URL:', depositPaymentInfo.value.payUrl)
    }
  } else {
    ElMessage.error('支付链接无效')
  }
}

const openDepositWechat = () => {
  if (depositPaymentInfo.value?.qrCode) {
    // 微信二维码通常是微信支付链接，需要验证
    if (depositPaymentInfo.value.payUrl && !validatePaymentUrl(depositPaymentInfo.value.payUrl)) {
      ElMessage.error('支付链接不安全，请联系客服')
      console.warn('Untrusted WeChat payment URL:', depositPaymentInfo.value.payUrl)
      return
    }

    if (/MicroMessenger/i.test(navigator.userAgent)) {
      window.location.href = depositPaymentInfo.value.qrCode
    } else {
      ElMessage.info('请使用微信扫描二维码完成支付')
    }
  } else {
    ElMessage.error('微信支付链接无效')
  }
}

const openDepositBankPay = () => {
  if (depositPaymentInfo.value?.payUrl) {
    if (validatePaymentUrl(depositPaymentInfo.value.payUrl)) {
      window.open(depositPaymentInfo.value.payUrl, '_blank')
    } else {
      ElMessage.error('支付链接不安全，请联系客服')
      console.warn('Untrusted bank payment URL:', depositPaymentInfo.value.payUrl)
    }
  } else {
    ElMessage.error('银行支付链接无效')
  }
}

// 请求频率限制器
const requestLimiter = {
  lastRequest: 0,
  minInterval: 3000, // 3秒最小间隔

  canRequest() {
    const now = Date.now()
    if (now - this.lastRequest < this.minInterval) {
      return false
    }
    this.lastRequest = now
    return true
  }
}

// 支付链接白名单验证
const TRUSTED_PAYMENT_DOMAINS = [
  'pay.alipay.com',
  'pay.weixin.qq.com',
  'pay.bank.com',
  'openapi.alipay.com',
  'api.mch.weixin.qq.com'
]

const validatePaymentUrl = (url) => {
  try {
    const urlObj = new URL(url)
    return TRUSTED_PAYMENT_DOMAINS.some(domain =>
      urlObj.hostname === domain || urlObj.hostname.endsWith('.' + domain)
    )
  } catch {
    return false
  }
}

// 移除自动轮询功能，改为手动刷新以提高安全性
const refreshDepositPaymentStatus = async () => {
  if (!currentDepositOrder.value) {
    ElMessage.error('订单信息不存在')
    return
  }

  // 请求频率限制
  if (!requestLimiter.canRequest()) {
    ElMessage.warning('请求过于频繁，请稍后再试')
    return
  }

  checkingDepositPayment.value = true

  try {
    // 使用安全的API调用而不是直接fetch
    const response = await checkDepositPaymentStatus(currentDepositOrder.value.orderId)

    if (response.code === 200) {
      const status = response.data.status

      if (status === 'paid') {
        // 支付成功 - 进行多重验证
        clearInterval(depositPaymentTimer.value)

        // 1. 验证订单时间（防止过快确认）
        const orderTime = new Date(currentDepositOrder.value.createTime).getTime()
        const now = new Date().getTime()

        if (now - orderTime < 10000) { // 10秒内完成支付可能是虚假的
          ElMessage.warning('支付确认过快，请稍后再试')
          checkingDepositPayment.value = false
          return
        }

        // 2. 验证金额一致性
        if (response.data.amount !== currentDepositOrder.value.amount) {
          ElMessage.error('支付金额不匹配，请联系客服')
          checkingDepositPayment.value = false
          return
        }

        // 3. 验证第三方支付平台回调
        if (!response.data.thirdPartyVerified) {
          ElMessage.warning('等待第三方支付平台确认，请稍后再试')
          checkingDepositPayment.value = false
          return
        }

        ElMessage.success('保证金支付成功！')

        // 关闭对话框并刷新数据
        depositDialogVisible.value = false
        resetDepositForm()

        // 刷新数据进行验证
        await Promise.all([
          getDepositStatsData(),
          getPaidServiceTypesData(),
          getDepositRecordsData()
        ])
      } else if (status === 'failed') {
        ElMessage.error(`支付失败：${response.data.failReason || '未知原因'}`)
        cancelDepositPayment()
      } else if (status === 'expired') {
        ElMessage.warning('支付已超时，请重新发起充值')
        cancelDepositPayment()
      } else {
        ElMessage.info('支付处理中，请在第三方支付平台完成支付后再次刷新')
      }
    } else if (response.code === 404) {
      ElMessage.error('订单不存在或已失效')
      cancelDepositPayment()
    } else {
      throw new Error(response.message || '查询支付状态失败')
    }
  } catch (error) {
    console.error('查询支付状态失败:', error)
    ElMessage.error('查询支付状态失败，请检查网络连接后重试')
  } finally {
    checkingDepositPayment.value = false
  }
}

const cancelDepositPayment = () => {
  clearInterval(depositPaymentTimer.value)
  depositDialogVisible.value = false
  resetDepositForm()
  ElMessage.info('已取消支付')
}

// 监听筛选条件变化
watch(filterType, async () => {
  currentPage.value = 1
  await getDepositRecordsData()
})

// 页面初始化
onMounted(async () => {
  console.log('保证金管理页面已加载')

  try {
    await Promise.all([
      getDepositStatsData(),
      getServiceTypesData(),
      getPaidServiceTypesData(),
      getDepositRecordsData(),
      getDeductionPriorityData()
    ])
    console.log('✅ 保证金管理数据加载完成')
  } catch (error) {
    console.error('❌ 保证金管理数据加载失败:', error)
    ElMessage.error('页面数据加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.deposit-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}

.stat-card.frozen .stat-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.stat-card.available .stat-icon {
  background: linear-gradient(135deg, #10b981, #059669);
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #6b7280, #4b5563);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 保证金要求 */
.deposit-requirements-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.requirements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 10px 0;
}

.requirement-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.requirement-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.service-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: white;
}

.service-icon.icon-laundry {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-icon.icon-shoes {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.service-icon.icon-pet {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.service-icon.icon-bag {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.service-icon.icon-bedding {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.service-icon.icon-car {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
}

.service-icon.icon-home {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
}

.service-icon.icon-plumbing {
  background: linear-gradient(135deg, #89f7fe, #66a6ff);
}

.service-icon.icon-default {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-info {
  flex: 1;
}

.service-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.service-desc {
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 6px;
}

.deposit-amount {
  font-size: 14px;
  font-weight: 600;
  color: #059669;
}

.service-status {
  margin-left: 12px;
}

/* 记录表格 */
.deposit-records-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 20px;
}

.header-filters {
  display: flex;
  align-items: center;
}

.amount-positive {
  color: #059669;
  font-weight: 600;
}

.amount-negative {
  color: #dc2626;
  font-weight: 600;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

/* 扣款设置 */
.deduction-settings-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 20px;
}

.deduction-settings {
  padding: 10px 0;
}

.setting-item {
  margin-bottom: 16px;
}

.setting-label {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  margin-right: 12px;
}

.setting-desc {
  margin-top: 12px;
  padding: 12px;
  background: #f3f4f6;
  border-radius: 6px;
}

.setting-desc p {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.5;
}

/* 表单提示 */
.form-tips {
  margin-top: 8px;
}

.form-tip {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 2px;
}

/* 支付页面样式 */
.payment-section {
  padding: 20px 0;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.payment-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
}

.payment-info .amount {
  margin: 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #059669;
}

.payment-info .order-id {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #6b7280;
}

.payment-timer {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  font-weight: 500;
  font-size: 16px;
}

.payment-content {
  margin-bottom: 20px;
}

.payment-method-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.qr-section {
  display: flex;
  gap: 30px;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.qr-instructions {
  flex: 1;
  max-width: 300px;
}

.qr-instructions p {
  margin: 8px 0;
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
}

.bank-section {
  text-align: center;
  padding: 20px;
}

.bank-instruction {
  margin: 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.payment-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.payment-status {
  text-align: center;
  padding: 40px 20px;
}

.payment-status .el-icon {
  font-size: 32px;
  color: #3b82f6;
  margin-bottom: 12px;
}

.payment-status p {
  margin: 0;
  color: #6b7280;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .deposit-management {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .requirements-grid {
    grid-template-columns: 1fr;
  }

  .requirement-item {
    flex-direction: column;
    text-align: center;
  }

  .service-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 12px 12px 0 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.stat-card .el-card__body) {
  padding: 0;
}
</style>